<template>
	<view>
		<view>
			<!-- 状态栏 -->
			<view class="statusBar" :style="'height:'+statusBarHeight+'px'"></view>
			<view class="myheader padding-sm  flex justify-between">
				<view class="font-sub-title">
					<text class="cuIcon-back margin-right-ssm" @click="back()"></text>
					连接设备
				</view>
				<view @click="refresh">
					<text class="font-sub-title cuIcon-refresh"></text>
				</view>
			</view>
		</view>
		<view  v-if="bindName!=''" class="flex justify-between padding" style="border-bottom: 1px solid #c3c3c3;">
			<view>{{bindName}}</view><view class="text-blue">当前绑定设备</view><view :class="state==0?'text-red':'text-green'">{{state==0?'已断开':'已连接'}}</view>
		</view>
		<view  v-if="bindName==''&&bleList.length!=0" class="flex justify-between padding" style="border-bottom: 1px solid #c3c3c3;">
			<view class="text-blue">没有绑定设备，请从下面列表中选择自己的设备绑定！</view>
		</view>
		<view v-if="bleList.length!=0">
			<view v-for="data in bleList" v-if="data.deviceId!=bindMac" class="flex justify-between padding" style="border-bottom: 1px solid #c3c3c3;" @click="connect(data.deviceId,data.name)">
				<view>{{data.name}}</view><view class="text-blue">{{data.RSSI}}dBm</view>
			</view>
		</view>
		<view class="text-red padding">
			小贴士:为了手环更精确地测量，首次连接设备后需进入“我的设备->设备基本参数”编辑基本健康状况。
		</view>
	</view>
</template>

<script>
	const bandSDK = uni.requireNativePlugin('BandSDK')
	var that;
	export default {
		data() {
			return {
				statusBarHeight: Vue.prototype.StatusBar,
				bleList:[],
				bindMac:uni.getStorageSync("bindMac")||'',
				state:0,
				bindName:uni.getStorageSync("bindName")||'',
				isOpen:false
			}
		},
		onLoad() {
			//在页面加载时候初始化蓝牙适配器
			uni.openBluetoothAdapter({
				success: e => {
					that.isOpen=true
					// 初始化完毕开始搜索
					that.refresh();
				},
				fail: e => {
					uni.showToast({
						"title":'初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg),
						"position":"bottom",
						"icon":"none"
					})
					console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
				}
			});
		},
		onShow() {
			that = this;
			this.refresh()
			plus.geolocation.getCurrentPosition(function(res){
					
				},function(err){
					if(err.code==1){
						uni.showToast({
							"title":"请打开GPS定位或检查应用定位权限",
							"position":"bottom",
							"icon":"none"
						})
					}else if(err.code==2){
						uni.showToast({
							"title":'定位失败，由于设备当前 GPS 状态差（或网络不畅）,建议持设备到相对开阔的露天场所再次尝试',
							"position":"bottom",
							"icon":"none"
						})
					}
				}
			)
		},
		methods: {
			startBluetoothDeviceDiscovery() {
				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
				setTimeout(function() {
					if (that.isOpen) {
						uni.startBluetoothDevicesDiscovery({
							success: res => {
								setTimeout(function(){
									that.getBluetoothDevices();
									that.stopBluetoothDevicesDiscovery();
									uni.hideLoading()
								},5000)
							},
							fail: res => {
								uni.showToast({
									icon: "none",
									title: "查找设备失败！",
									duration: 3000
								})
							}
						});
					} else {
						uni.showToast({
							icon: "none",
							title: "未初始化蓝牙配饰器！",
							duration: 3000
						})
					}
				}, 300);
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						
					},
					fail: e => {
					}
				});
			},
			/**
			 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			 */
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						that.bleList = []
						var len = res.devices.length
						for(var i=0;i<len;i++){
							if(res.devices[i].name.replace(" ","").indexOf("P11PLUS")!=-1){
								that.bleList.push(res.devices[i])
							}
						}
					}
				});
			},
			back() {
				uni.navigateBack();
			},
			refresh(){
				bandSDK.connectState(res => {
					if (res == "disconnected") {
						that.state=0
					} else if(res=="connected"){
						that.state=1
					}
				})
				uni.showLoading({
					"title":"搜索中..."
				})
				that.startBluetoothDeviceDiscovery();
			},
			connect(mac,name){
				bandSDK.disconnectBle();
				uni.removeStorageSync("bindMac")
				uni.removeStorageSync("bindName")
				uni.showLoading({
					"title":"连接中..."
				})
				bandSDK.connectBle({
					'mac':mac
				},res=>{
					if(res=='success'){
						uni.hideLoading()
						uni.showToast({
							"title":"连接成功！"
						})
						uni.setStorageSync("isFirstConnect",true);
						uni.setStorageSync("bindMac",mac);
						uni.setStorageSync("bindName",name);
						uni.removeStorageSync("userDisconnect")
						uni.$emit("refresh",{})
						setTimeout(function(){
							uni.switchTab({
								"url":"/pages/index/index"
							})
						},1000)
					}
				})
			}
		}
	}
</script>

<style>

</style>
